//
//  YWInspectionRecordDetailViewController.m
//  maintain
//
//  Created by Kyo on 16/5/27.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWInspectionRecordDetailViewController.h"
#import "UIScrollView+EmptyDataSet.h"
#import "YWMacro.h"
#import "UIColor+CustomColors.h"
#import "YWInspectionEquipmentRecord.h"
#import "YWInspectionMissionManager.h"
#import "YWCommonTool.h"
#import "UIView+Extension.h"
#import "YWInspectionMissionModel.h"
#import "YWInspectionLineRecord.h"
#import "YWInspectionMissionModel.h"
#import "YWInspecEquipmentRecordDetailTableViewController.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWEquipment.h"
#import "YWInspectionTimeLineCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "Masonry.h"
#import "UILabel+AttributedText.h"
#import "YWInspecLocationRecordDetailTableViewController.h"

@interface YWInspectionRecordDetailViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,UITableViewDataSource,UITableViewDelegate>{
    BOOL hasRecord;
    NSInteger finishPointCount;
    NSInteger troublePointCount;
}
@property (nonatomic, strong) UITableView *detailTableView;
@property (nonatomic, strong) NSArray *timeLineDataArray;

@property (nonatomic, strong) UIView* headView;
@property (nonatomic, strong) UILabel *missionSequeceLabel;
@property (nonatomic, strong) UILabel *buildingNameLabel;
@property (nonatomic, strong) UILabel *patrolLineNameLabel;
@property (nonatomic, strong) UILabel *executorLabel;
@property (nonatomic, strong) UILabel *recordTimeLabel;
@property (nonatomic, strong) UILabel *totalPointLabel;
@property (nonatomic, strong) UILabel *finishPointLabel;
@property (nonatomic, strong) UILabel *troublePointLabel;
@end

@implementation YWInspectionRecordDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"recordsDetail", nil);
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.detailTableView.backgroundColor = [UIColor customBackgroudColor];
    self.detailTableView.tableHeaderView = self.headView;
    self.detailTableView.tableFooterView = [[UIView alloc] init];
    
    BOOL existEquipmentOrLocation = NO;
    NSInteger inspectionLineId = self.lineRecord.inspectionLineId > 0 ? self.lineRecord.inspectionLineId : self.lineRecord.inspectionLine.inspectionLineId;
    if (self.lineRecord.recordType == YWInspectionLineRecordTypeEquipment) {
        existEquipmentOrLocation = [[YWInspectionMissionManager shareManager] isExistEquipmentWithLineId:inspectionLineId];
    }else{
        existEquipmentOrLocation = [[YWInspectionMissionManager shareManager] isExistLocationWithLineId:inspectionLineId];
    }
    
    if (!existEquipmentOrLocation && inspectionLineId!=0) {
        YWWeakSelf(weakSelf);
        [[YWInspectionMissionManager shareManager] requestInspectionLineWithInspectionLineId:inspectionLineId Complete:^(YWInspectionLineModel *inspectionLine) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (inspectionLine) {
                    [weakSelf requestDetailRecordWithLine];
                }
            });
        }];
    }else{
        [self requestDetailRecordWithLine];
    }
}
- (void)requestDetailRecordWithLine{
    YWWeakSelf(weakSelf);
    YWInspectionEquipmentRecordType type = (self.lineRecord.recordType == YWInspectionLineRecordTypeEquipment)?YWInspectionEquipmentRecordTypeEquipment:YWInspectionEquipmentRecordTypeLocation;
    [[YWInspectionMissionManager shareManager] requestInspectionEquipmentRecord:weakSelf.lineRecord.uniqueTag type:type WithComplete:^(BOOL success) {
        [self loadTimeLineData];
        if (success) {
            [weakSelf.buildingNameLabel labelText:NSLocalizedString(@"locationFormatter", nil) withAttributedText:[weakSelf buildingName] andAttributedColor:[UIColor blackColor]];
        }
    }];
}

- (NSArray *)timeLineDataArray{
    if (!_timeLineDataArray) {
        _timeLineDataArray = [NSArray array];
    }
    return _timeLineDataArray;
}

- (void)loadTimeLineData{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        YWInspectionLineModel *line = [[YWInspectionMissionManager shareManager] inspectionLineWithLineId:self.lineRecord.inspectionLineId];
        NSArray *array = nil;
        if (self.lineRecord.recordType == YWInspectionLineRecordTypeEquipment) {
            array = [[YWInspectionMissionManager shareManager] timeLineViewDataWithInspectionRecord:self.lineRecord];
        }else{
            array = [[YWInspectionMissionManager shareManager] timeLineViewDataWithLocationRecord:self.lineRecord];
        }
        _timeLineDataArray = array;
        finishPointCount = 0;
        troublePointCount = 0;
        
        [_timeLineDataArray enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
            YWInspectionEquipmentRecord *equipmentRecord = [dic objectForKey:YWMissionManagerDicRecordObj];
            if (equipmentRecord) {
                hasRecord = YES;
            }else{
                hasRecord = NO;
            }
            YWInspectionEquipmentStatusType type = [[dic objectForKey:YWMissionManagerDicStatusType]integerValue];
            if (YWInspectionEquipmentStatusTypeFinishNormal == type){
                finishPointCount++;
            }else if (YWInspectionEquipmentStatusTypeFinishTrouble == type){
                finishPointCount++;
                troublePointCount++;
            }
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.timeLineDataArray = array;
            [self.detailTableView reloadData];
            [self setupPointLabel];
        });
    });
}

-(UITableView *)detailTableView{
    if (!_detailTableView) {
        UITableView* tableView = [[UITableView alloc] init];
        [tableView registerClass:[YWInspectionTimeLineCell class] forCellReuseIdentifier:inspectionTimeLineCellIdentifier];
        [self.view addSubview:tableView];
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.separatorColor = [UIColor customLineColor];
        tableView.estimatedRowHeight = 44.0f;
        tableView.rowHeight = UITableViewAutomaticDimension;
        _detailTableView = tableView;
    }
    return _detailTableView;
}

#pragma mark - UITableViewDataSource
//- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
//{
//    return [tableView fd_heightForCellWithIdentifier:inspectionTimeLineCellIdentifier cacheByIndexPath:indexPath configuration:^(YWInspectionTimeLineCell *cell) {
//        cell.fd_enforceFrameLayout = NO;
//        cell.dicData = self.timeLineDataArray[indexPath.row];
//    }];
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.timeLineDataArray.count;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    YWInspectionTimeLineCell *cell =[YWInspectionTimeLineCell cellWithTableView:tableView];
    NSDictionary *dic = self.timeLineDataArray[indexPath.row];
    YWInspectionEquipmentRecord *equipmentRecord = [dic objectForKey:YWMissionManagerDicRecordObj];
    if (equipmentRecord) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    cell.dicData = dic;
    return cell;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = self.timeLineDataArray[indexPath.row];
    YWInspectionEquipmentRecord *equipmentRecord = [dic objectForKey:YWMissionManagerDicRecordObj];
    if (equipmentRecord) {
        if (equipmentRecord.recordType == YWInspectionEquipmentRecordTypeEquipment && equipmentRecord.equipment) {
            YWInspecEquipmentRecordDetailTableViewController *equipmentDetailRecordVC = [[YWInspecEquipmentRecordDetailTableViewController alloc] init];
            equipmentDetailRecordVC.inspectionEquipmentRecord = equipmentRecord;
            [self.navigationController pushViewController:equipmentDetailRecordVC animated:YES];
        }else{
            YWInspecLocationRecordDetailTableViewController *locationRecordVC = [[YWInspecLocationRecordDetailTableViewController alloc] init];
            locationRecordVC.inspectionEquipmentRecord = equipmentRecord;
            [self.navigationController pushViewController:locationRecordVC animated:YES];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==0 && self.lineRecord.inspectionLineId != 0 && self.lineRecord.result==YWInspectionLineRecordResultSystem && !hasRecord) {
        return 80;
    }else{
        return 0;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section==0 && self.lineRecord.inspectionLineId != 0 && self.lineRecord.result==YWInspectionLineRecordResultSystem && !hasRecord) {
        UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.recordTimeLabel.frame), SCREEN_WIDTH, 80)];
        tipLabel.font = kContentFont;
        tipLabel.numberOfLines = 2;
        tipLabel.textAlignment = NSTextAlignmentCenter;
        tipLabel.backgroundColor = [UIColor customBackgroudColor];
        NSString *startTimeStr = [YWCommonTool showTime:self.lineRecord.startTime/1000 andFormatter:KTimeFormatShortTime];
        NSString *endTimeStr = [YWCommonTool showTime:self.lineRecord.endTime/1000 andFormatter:KTimeFormatShortTimeDateYear];
        tipLabel.text = [NSString stringWithFormat:@"%@ - %@%@",startTimeStr,endTimeStr,NSLocalizedString(@"systemAutogenerationInspectionRecord", nil)];
        return tipLabel;
    }else{
        return nil;
    }
}

- (UILabel *)missionSequeceLabel{
    if (!_missionSequeceLabel) {
        UILabel *missionSequeceLabel = [[UILabel alloc]init];
        missionSequeceLabel.font = kContentFont;
        missionSequeceLabel.textColor = [UIColor customTextGrayColor];
//        YWInspectionMissionModel *mission = [[YWInspectionMissionManager shareManager] inspectionMissionWithMissionId:self.lineRecord.inspectionMissionId];
        NSString *recordSequence = self.lineRecord.recordSequence;
        [missionSequeceLabel labelText:NSLocalizedString(@"recordSequence", nil) withAttributedText:recordSequence.length?recordSequence:NSLocalizedString(@"none", nil) andAttributedColor:[UIColor customYellowColor]];
        _missionSequeceLabel = missionSequeceLabel;
    }
    return _missionSequeceLabel;
}

- (UILabel *)buildingNameLabel{
    if (!_buildingNameLabel) {
        UILabel *buildingNameLabel = [[UILabel alloc]init];
        buildingNameLabel.font = kContentFont;
        buildingNameLabel.textColor = [UIColor customTextGrayColor];
        buildingNameLabel.numberOfLines = 0;
        NSString *buildingStr = [self buildingName];
        [buildingNameLabel labelText:NSLocalizedString(@"locationFormatter", nil) withAttributedText:buildingStr andAttributedColor:[UIColor blackColor]];
        _buildingNameLabel = buildingNameLabel;
    }
    return _buildingNameLabel;
}

- (NSString*)buildingName{
    NSArray *equipmentRecords = [[YWInspectionMissionManager shareManager] inspectionEquipmentRecordWithUniqueTag:self.lineRecord.uniqueTag];
    YWBuilding *building = nil;
    if (equipmentRecords.count) {
        YWInspectionEquipmentRecord *record = equipmentRecords.count?equipmentRecords[0]:nil;
        if (record.equipment) {
            building = [[YWBuildingManager shareManager] buildingWithEquipmentId:record.equipment.equipmentId];
        }else{
            building = [[YWBuildingManager shareManager] buildingWithLocationId:record.locationId];
        }
        
    }else{
//        YWInspectionLineModel *line = [[YWInspectionMissionManager shareManager] inspectionLineWithLineId:self.lineRecord.inspectionLineId];
        if (self.lineRecord.recordType == YWInspectionLineRecordTypeEquipment) {
            NSArray *allEquipments = [[YWInspectionMissionManager shareManager] allInspectionEquipmentWithLineId:self.lineRecord.inspectionLineId];
            YWEquipment *equipment = allEquipments.count?allEquipments[0]:nil;
            building = [[YWBuildingManager shareManager] buildingWithEquipmentId:equipment.equipmentId];
        }else{
            NSArray *allLocations = [[YWInspectionMissionManager shareManager] allInspectionLocationWithInspectionLineId:self.lineRecord.inspectionLineId];
            YWInspectionLineLocationRel *locationRel = allLocations.count? allLocations[0]:nil;
            building = [[YWBuildingManager shareManager] buildingWithLocationId:locationRel.locationId];
        }
    }
    return building.buildingName.length>0?building.buildingName:NSLocalizedString(@"unknowBuilding", nil);
}

-(UILabel *)patrolLineNameLabel{
    if (!_patrolLineNameLabel) {
        UILabel *patrolLineNameLabel = [[UILabel alloc]init];
        patrolLineNameLabel.font = kContentFont;
        patrolLineNameLabel.numberOfLines = 0;
        patrolLineNameLabel.textColor = [UIColor customTextGrayColor];
        if (self.lineRecord.inspectionLineId == 0) {
            [patrolLineNameLabel labelText:NSLocalizedString(@"lineFormatter", nil) withAttributedText:NSLocalizedString(@"tempInspection", nil) andAttributedColor:[UIColor blackColor]];
        }else{
            YWInspectionLineModel *lineModel = [[YWInspectionMissionManager shareManager] inspectionLineWithLineId:self.lineRecord.inspectionLineId];
//            patrolLineNameLabel.text = [NSString stringWithFormat:@"路线: %@",lineModel.inspectionLineName?:@""];
            [patrolLineNameLabel labelText:NSLocalizedString(@"lineFormatter", nil) withAttributedText:lineModel.inspectionLineName?:@"" andAttributedColor:[UIColor blackColor]];
        }
        _patrolLineNameLabel = patrolLineNameLabel;
    }
    return _patrolLineNameLabel;
}

-(UILabel *)executorLabel{
    if (!_executorLabel) {
        UILabel *executorLabel = [[UILabel alloc]init];
        executorLabel.font = kContentFont;
        executorLabel.textColor = [UIColor customTextGrayColor];
        executorLabel.numberOfLines = 0;
        NSString *name = nil;
        if (self.lineRecord.inspectionLineId != 0 && self.lineRecord.result==YWInspectionLineRecordResultSystem && !hasRecord) {
            name = NSLocalizedString(@"noManToInspection", nil);
        }else{
            name = [YWCommonTool handlerNamesWithHandlers:self.lineRecord.executors];
        }
        [executorLabel labelText:NSLocalizedString(@"inspectionExecutorFormatter", nil) withAttributedText:name.length? name:NSLocalizedString(@"noManToInspection", nil) andAttributedColor:[UIColor customYellowColor]];
        _executorLabel = executorLabel;
    }
    return _executorLabel;
}

-(UILabel *)recordTimeLabel{
    if (!_recordTimeLabel) {
        UILabel *recordTimeLabel = [[UILabel alloc]init];
        recordTimeLabel.font = kContentFont;
        recordTimeLabel.textColor = [UIColor customTextGrayColor];
        NSString *startTimeStr = [YWCommonTool showTime:self.lineRecord.startTime/1000 andFormatter:KTimeFormatShortTime];
        NSString *endTimeStr = [YWCommonTool showTime:self.lineRecord.endTime/1000 andFormatter:KTimeFormatShortTimeDateYear];
//        recordTimeLabel.text = [NSString stringWithFormat:@"巡查时间: %@ - %@",startTimeStr,endTimeStr];
        [recordTimeLabel labelText:NSLocalizedString(@"inspectionTime", nil) withAttributedText:[NSString stringWithFormat:@"%@ - %@",startTimeStr,endTimeStr] andAttributedColor:[UIColor blackColor]];
        _recordTimeLabel = recordTimeLabel;
    }
    return _recordTimeLabel;
}

- (UILabel *)totalPointLabel{
    if (!_totalPointLabel) {
        UILabel *label = [[UILabel alloc]init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayColor];
        _totalPointLabel = label;
        [_totalPointLabel labelText:NSLocalizedString(@"inspectionCount", nil) withAttributedText:@"0个" andAttributedColor:[UIColor blackColor]];
    }
    return _totalPointLabel;
}

- (UILabel *)finishPointLabel{
    if (!_finishPointLabel) {
        UILabel *label = [[UILabel alloc]init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayColor];
        _finishPointLabel = label;
        [_finishPointLabel labelText:@"已完成: " withAttributedText:[NSString stringWithFormat:@"%ld个",(long)finishPointCount] andAttributedColor:[UIColor blackColor]];
    }
    return _finishPointLabel;
}

- (UILabel *)troublePointLabel{
    if (!_troublePointLabel) {
        UILabel *label = [[UILabel alloc]init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayColor];
        _troublePointLabel = label;
        [_troublePointLabel labelText:NSLocalizedString(@"unnormalPoint", nil) withAttributedText:[NSString stringWithFormat:@"%ld个",(long)troublePointCount] andAttributedColor:[UIColor customRedColor]];
    }
    return _troublePointLabel;
}

- (void)setupPointLabel{
    NSInteger count = self.timeLineDataArray.count;
    [self.totalPointLabel labelText:NSLocalizedString(@"inspectionCount", nil) withAttributedText:[NSString stringWithFormat:@"%ld个",(long)count] andAttributedColor:[UIColor blackColor]];
    [self.finishPointLabel labelText:@"已完成: " withAttributedText:[NSString stringWithFormat:@"%ld个",(long)finishPointCount] andAttributedColor:[UIColor blackColor]];
    [self.troublePointLabel labelText:NSLocalizedString(@"unnormalPoint", nil) withAttributedText:[NSString stringWithFormat:@"%ld个",(long)troublePointCount] andAttributedColor:[UIColor customRedColor]];
}

-(UIView *)headView{
    if (!_headView) {
        UIView *headView = [[UIView alloc]init];
        headView.backgroundColor = [UIColor whiteColor];
        CGFloat labelW = SCREEN_WIDTH - kMarginW*2;
        [self.missionSequeceLabel setFrame:CGRectMake(kMarginW, kGapH, labelW, kLabelH)];
        
        CGFloat buildingH = [YWCommonTool getHeightOfLabel:self.buildingNameLabel.text andWidth:labelW andFont:self.buildingNameLabel.font andMinHeight:kLabelH];
        [self.buildingNameLabel setFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.missionSequeceLabel.frame), labelW, buildingH)];
        
        CGFloat lineNameH = [YWCommonTool getHeightOfLabel:self.patrolLineNameLabel.text andWidth:labelW andFont:self.patrolLineNameLabel.font andMinHeight:kLabelH];
        [self.patrolLineNameLabel setFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.buildingNameLabel.frame), labelW, lineNameH)];
        CGFloat executorH = [YWCommonTool getHeightOfLabel:self.executorLabel.text andWidth:labelW andFont:self.executorLabel.font andMinHeight:kLabelH];
        [self.executorLabel setFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.patrolLineNameLabel.frame), labelW, executorH)];
        [self.recordTimeLabel setFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.executorLabel.frame), labelW, kLabelH)];
        
        [self.totalPointLabel setFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.recordTimeLabel.frame), labelW, kLabelH)];
        [self.finishPointLabel setFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.totalPointLabel.frame), (labelW-kMarginW)/2, kLabelH)];
        [self.troublePointLabel setFrame:CGRectMake(CGRectGetMaxX(self.finishPointLabel.frame)+kMarginW, CGRectGetMaxY(self.totalPointLabel.frame), (labelW-kMarginW)/2, kLabelH)];
        
        [headView addSubview:self.missionSequeceLabel];
        [headView addSubview:self.buildingNameLabel];
        [headView addSubview:self.patrolLineNameLabel];
        [headView addSubview:self.executorLabel];
        [headView addSubview:self.recordTimeLabel];
        [headView addSubview:self.totalPointLabel];
        [headView addSubview:self.finishPointLabel];
        [headView addSubview:self.troublePointLabel];
        
        [headView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, buildingH+lineNameH+executorH+kLabelH*4+kGapH*1.5)];
        _headView = headView;
    }
    return _headView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
